package com.common.android.utils.audio;

import java.io.File;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;

import com.common.android.utils.SdCardUtils;
import com.common.android.utils.ToastUtils;
import com.nd.android.u.allcommon.R;
import com.product.android.business.LogConst;
import com.product.android.utils.LogUtils;

/**
 * ClassName:AudioRecordOperationManager
 * Function:  录音管理类（含UI操作）
 * Reason:	 
 * @author   cb		
 * @version  Ver 1.3.3_modularization
 * @Date	 2014	2014-2-14		下午4:12:21
 *
 * @see 	 
 */
public abstract class AudioRecordOperationManager {
	public interface IRecordOperation{
		public void showMenuWindow();
		public boolean audioStart();
		public int getModle();
		public void switchImg();
		public void audioFinish();
		public void hideMenuWindow();
		public void setAudioHandler(Handler handler);
	}
	private Context mContext;
	private Button mRecordButton;
	private boolean isCancel = false; // 是否取消录音
	private IRecordOperation mRecordOperation;
	public static final int MSG_UPLOAD = 100;
	private boolean mIsProtecting=false;
	
	private int mNormalResId = 0;	
	private int mSelectedResId = 0;

	public class RecordType {
		public static final int CHAT_RECORD = 0;// 聊天录音
		public static final int FLOWER_MESSAGE_RECORD = 1;// 留言录音
	}

	public void setRecordOperation(IRecordOperation operation){
		mRecordOperation=operation;
		mRecordOperation.setAudioHandler(audioHandler);
	}
	public AudioRecordOperationManager(Context context, Button button) {
		mContext = context;
		mRecordButton = button;
		mRecordOperation= new TalkPopWindow((Activity) context,button);
		mRecordOperation.setAudioHandler(audioHandler);
		button.setOnTouchListener(listener);
	}

	public void setBgRes(int normalResId, int selectedResId){
		mNormalResId = normalResId;
		mSelectedResId = selectedResId;
	}
	private boolean hasSend = false;// 用于标记当前是否已经发送
	
	private OnTouchListener listener = new OnTouchListener() {

		private boolean bool;
		private boolean isStart = true;

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			int y;
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
			    recoading();
				if (mIsProtecting){
					ToastUtils.display(R.string.chat_error_frequence_record);
					return false;
				}
				mIsProtecting=true;
				mRecordButton.postDelayed(new Runnable() {
					public void run() {
						mIsProtecting=false;
					}
				},2000);
				hasSend = false;
				isCancel = false;
				if (!SdCardUtils.isSdCardExist()) {
					ToastUtils.display(mContext, R.string.audio_no_sdcard);
					isStart = false;
				} else {
					AudioPlayer.getInstance().stopPlay();
					mRecordOperation.showMenuWindow();
					bool = mRecordOperation.audioStart();
//					mRecordButton.setBackgroundResource(R.drawable.bt_talk_bg_over);
					Log.i("HYK", "mSelectedResId = " + mSelectedResId);
					if(mSelectedResId > 0){
						mRecordButton.setBackgroundResource(mSelectedResId);
					}
					mRecordButton.setText(R.string.audio_finish);
					isStart = true;
					// 屏蔽ScrollView和viewpage的事件拦截
					v.getParent().requestDisallowInterceptTouchEvent(true);
				}
				break;
			case MotionEvent.ACTION_MOVE:
				if (isStart) {
					y = (int) event.getY();
					int model=mRecordOperation.getModle();
					if ((y < -100 && model == AudioRecordManager.STATE_RECORD)
							|| (y > -100 && model == AudioRecordManager.STATE_CANCEL)) {
						mRecordOperation.switchImg();
						
					}
				}
				break;
			case MotionEvent.ACTION_UP:
			case MotionEvent.ACTION_CANCEL:
				y = (int) event.getY();
				if (y < -100)
					isCancel = true;
				if (isStart && !hasSend) {
					if (bool && !hasSend) {
						mRecordOperation.audioFinish();
						setNormalButton();
//						mRecordButton.postDelayed(new Runnable() {
//							public void run() {
//								//某些机子上会出现录音录不完整的情况，所以加个延时结束
//								
//							}
//						}, 200);
					}
				}
				break;
			}
			return false;
		}
	};
    
	private void setNormalButton() {
		mRecordOperation.hideMenuWindow();
		mRecordButton.setText(R.string.audio_start);
//		mRecordButton.setBackgroundResource(R.drawable.bt_talk_bg_normal);
		// 恢复ScrollView和viewpage的事件拦截
		Log.i("HYK", "mNormalResId = " + mNormalResId);
		if(mNormalResId > 0){
			mRecordButton.setBackgroundResource(mNormalResId);
		}
		mRecordButton.getParent().requestDisallowInterceptTouchEvent(false);
	}

	private Handler audioHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				LogUtils.d(LogUtils.TIMECOST, LogConst.IM24 + System.currentTimeMillis());
				break;
			}
			setNormalButton();
			if (!hasSend) {
				hasSend = true;
				Bundle bundle = msg.getData();
				if (bundle != null && bundle.containsKey("fileName")) {
					String fileName = bundle.getString("fileName");
					int duration=bundle.getInt("duration");
					if (TextUtils.isEmpty(fileName)){
						return;
					}
					if (isCancel) {
                       new File(fileName).delete();
					} else {
						sendAudioMsg(fileName,duration);
					}
				}
			}
		}
	};
	
	protected abstract void sendAudioMsg(String fileName,int duration);
	
	//BUG #59481 by mn
	//录音时需要停止播放
	protected abstract void recoading();
}
